package com.laijiale.server;



import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author laijiale
 * @date 2025年01月08日 20:48
 */

@Slf4j
@Component
@ServerEndpoint("/barrage/{userId}")
public class BarrageServer{
    /**用于存储每个ws客户端的Session实例：ConcurrentHashMap保证线程安全，static保证实例唯-*/
         private static final Map<Long, Session> CLIENTS = new ConcurrentHashMap<>();
         /**当WS客户端上线时触发*/
          @OnOpen
          public void onOpen(@PathParam("userId") Long userId, Session session) {
           //将客户端唯一标识及其Session实例存入Map
           CLIENTS.put(userId, session);
           log.info("{}号用户上线了",userId);
          }
          /**当WS客户端下线时触发...*/
          @OnClose
          public void onClose(@PathParam("userId") Long userId, Session session) {
           //从Map中移除该客户端和及其Session实例
           CLIENTS.remove(userId);
           log.info("{}号用户下线了",userId);
          }
          /**当WS客户端连接WS服务端异常时触发*/
          @OnError
          public void onError(@PathParam("userId") Long userId, Throwable e, Session session) {
           log.error("{}号用户连接或者通信异常", userId, e);
          }
          /**当WS服务端接收到弹幕消息的时候触发：对Map中的全部在线的WS客户端群发弹幕消息...*/
         @OnMessage
         public void onMessage(@PathParam("userId") Long userId, String msg,Session session){
            //遍历Map容器并向所有在线的客户端推送该消息
            CLIENTS.keySet().forEach(key -> CLIENTS.get(key).getAsyncRemote().sendText(msg));
            log.info("{}号用户发来弹幕：{}",userId,msg);
           }
          }